#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h>		// arduino IDE upload with spiffs -> https://github.com/esp8266/Arduino/blob/master/doc/filesystem.md
					// PIO upload with spiffs -> http://docs.platformio.org/en/latest/platforms/espressif8266.html#uploading-files-to-file-system-spiffs

#include "CarCtrl.h"

#define DP 5  //Data Pin -> [ DS ]
#define LP 16  //Latch Pin -> [ ST_CP ]
#define CP 2  //Clock Pin -> [ SH_CP ]

#define EN_FL  12 // enable pin front left.
#define EN_FR  13 // enable pin front right.
#define EN_BL  14 // enable pin back left.
#define EN_BR  4 // enable pin back right.

CarCtrl CAR( EN_FL, EN_FR, EN_BL, EN_BR, DP, LP, CP );
ESP8266WebServer server(80);

void setup()
{
	Serial.begin(115200);
	
	//WiFi.begin("ITMax02", "SZitmax3690");
	WiFi.begin("huyiice", "[13590367145]");
	while (WiFi.status() != WL_CONNECTED)
	{
		delay(500);
		Serial.print(".");
	}
	Serial.print("\n IP address: ");	Serial.println(WiFi.localIP());


	Serial.println(SPIFFS.begin() ? "SPIFFS success!" : "SPIFFS Fail!");

	server.on("/", [](){
		if (SPIFFS.exists("/index.html"))
		{
			File file = SPIFFS.open("/index.html", "r");
			server.streamFile(file, "text/html");
		}
	});

	server.on("/test",[](){
		if (SPIFFS.exists("/test.html"))
		{
			File file = SPIFFS.open("/test.html", "r");
			server.streamFile(file, "text/html");
		}		
		});


	server.on("/cmd", [](){
		int dir   = 0;
		int speed = 0;

		Serial.print("cmd as :");
		for (int i = 0; i < server.args(); i++)
		{
			String name = server.argName(i);
			String value = server.arg(i);
			Serial.print("argname: "); Serial.print(name); Serial.print("\t value: \t"); Serial.print(value); Serial.print("\t");
			if (name == "dir")
			{
				if (value == "up")dir = CAR_DIR_UP;
				else if (value == "down")dir = CAR_DIR_DOWN;
				else if (value == "left")dir = CAR_DIR_LEFT;
				else if (value == "right")dir = CAR_DIR_RIGHT;
				else if (value == "release")dir = CAR_DIR_NONE;
			}
			Serial.println();

			if (name == "speed")
			{
				speed = value.toInt();
			}

			if(name == "status")
			{
				CAR.SetStatus(value);
			}

			//CAR.SetDirSpeed(dir, speed);
		}
		
		server.send(200, "text/plain", "OK");
	});
	server.onNotFound([](){server.send(200, "text/plain", "FILE Not Found\n\n"); });
	server.begin();

	CAR.Start();
}

void loop()
{
	server.handleClient();
/*
  Serial.println("first");
  digitalWrite(LP, LOW);
  shiftOut(DP, CP, MSBFIRST, 0x00);
  digitalWrite(LP, HIGH);
  delay(3000);
  Serial.println("second");
  digitalWrite(LP, LOW);
  shiftOut(DP, CP, MSBFIRST, 0x80);
  digitalWrite(LP, HIGH); 
  delay(3000);
  */
};
